<template>
  <div class="user-list">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 搜索栏 -->
        <el-form ref="filterUsers" :inline="true" :model="filterUsers" class="demo-form-inline">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="filterUsers.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="注册时间" prop="rangeDate">
            <el-date-picker
              v-model="filterUsers.rangeDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="onReset" :disabled="isLoading">重置</el-button>
            <el-button type="primary" @click="onSearch" :disabled="isLoading">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格部分 -->
      <el-table
        :data="users"
        stripe
        style="width: 100%"
        v-loading="isLoading">
        <el-table-column
          prop="id"
          label="用户ID"
          width="150">
        </el-table-column>
        <el-table-column
          prop="portrait"
          label="头像"
          width="100">
          <template slot-scope="scope">
          <img width="30px" :src="scope.row.portrait || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'">
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="用户名">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="注册时间">
          <!-- 时间过滤器 -->
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <el-switch
            v-model="scope.row.status"
            active-value="ENABLE"
            inactive-value="DISABLE"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleSelectedRole(scope.row)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页处理 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="filterUsers.currentPage"
      :page-sizes="[10, 15, 20]"
      :page-size="filterUsers.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
    <!-- 设置分配角色的弹出框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="dialogVisible"
      width="50%">
      <el-select v-model="roleIdList" multiple placeholder="请选择">
        <el-option
          v-for="item in roles"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <!-- 确认 & 取消 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllRoles, allocatedUserRole } from '@/services/role'
import { getUserPages, getUserRole } from '@/services/user'

export default {
  name: 'UserList',
  data () {
    return {
      // 筛选表单数组
      filterUsers: {
        currentPage: 1,
        pageSize: 10,
        phone: '',
        startCreateTime: '',
        endCreateTime: '',
        // 日期选择器
        rangeDate: []
      },
      // 获取的用户信息总条数
      totalCount: 0,
      // 存储用户信息
      users: [],
      isLoading: false,
      // 用于控制分配角色对话框是否显示
      dialogVisible: false,
      // 所有⻆⾊，对象示例的 option
      roles: [],
      // 选中⻆⾊对应的 value
      roleIdList: [],
      // 当前用户 ID
      currentId: null
    }
  },
  created () {
    // 分页加载用户信息
    this.loadUserPages()
  },
  methods: {
    // 每页有多少条数据
    handleSizeChange (val) {
      this.filterUsers.pageSize = val
      this.filterUsers.currentPage = 1
      this.loadUserPages()
    },
    // 处于第几页
    handleCurrentChange (val) {
      this.filterUsers.currentPage = val
      this.loadUserPages()
    },
    // 加载全部用户信息
    async loadUserPages () {
      this.isLoading = true
      const { rangeDate } = this.filterUsers
      if (rangeDate && rangeDate.length) {
        this.filterUsers.startCreateTime = rangeDate[0]
        this.filterUsers.endCreateTime = rangeDate[1]
      } else {
        this.filterUsers.startCreateTime = ''
        this.filterUsers.endCreateTime = ''
      }
      const { data } = await getUserPages(this.filterUsers)
      if (data.code === '000000') {
        this.users = data.data.records
        this.totalCount = data.data.total
        this.isLoading = false
      }
    },
    // 搜索栏查询按钮
    onSearch () {
      this.filterUsers.currentPage = 1
      this.loadUserPages()
    },
    // 搜索栏重置按钮
    onReset () {
      this.$refs.filterUsers.resetFields()
      this.loadUserPages()
    },
    // 保存对话框中内容
    async onSave () {
      console.log(this.currentId)
      console.log(this.roleIdList)
      // 点击确认，将分配角色信息提交给服务器
      const { data } = await allocatedUserRole({
        userId: this.currentId,
        roleIdList: this.roleIdList
      })
      if (data.code === '000000') {
        this.$message.success('保存成功')
      }
      // 关闭对话框
      this.dialogVisible = false
    },
    // 显示分配角色对话框
    async handleSelectedRole (rowData) {
      // 将当前行的 用户id 存储起来
      this.currentId = rowData.id
      // 显示分配角色的对话框
      this.dialogVisible = true
      // 请求所有角色的列表数据
      const { data } = await getAllRoles()
      if (data.code === '000000') {
        this.roles = data.data
      }
      // 请求当前用户已分配信息
      const { data: data2 } = await getUserRole(rowData.id)
      if (data2.code === '000000') {
        // 将 data数组中，每个对象的id单独存储起来
        this.roleIdList = data2.data.map(item => item.id)
      }
    }
  },
  filters: {
    // 日期过滤器
    dateFormat (date) {
      date = new Date(date)
      return `
        ${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}
        ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}
      `
    }
  }
}
</script>

<style lang="scss" scoped></style>
